package org.example.uti;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class esUtil {

    @Value("${elasticsearch.hostAndProts}")
    private String hostPort;




    @Bean
    public RestHighLevelClient restHighLevelClient(){
// 初始化连接ES的HttpHost信息
        String[] split = hostPort.split(":");

        HttpHost httpHost = new HttpHost(split[0], Integer.parseInt(split[1]));



        // 设置认证信息
        CredentialsProvider credentialsProvider = new
                BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,new
                UsernamePasswordCredentials("elastic","ZhengJinWei123!"));
// 构建时设置连接信息，基于set设置认证信息
        RestClientBuilder restClientBuilder = RestClient.builder(httpHost);
        restClientBuilder.setHttpClientConfigCallback(f ->
                f.setDefaultCredentialsProvider(credentialsProvider));


        // 构建连接ES的client对象
        RestHighLevelClient restHighLevelClient = new
                RestHighLevelClient(restClientBuilder);
// 返回
        return restHighLevelClient;
    }


}
